import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:icooker/model/meaildetail/CookStep.dart';
import 'package:icooker/model/meaildetail/MealDetailData.dart';
import 'package:icooker/providers/meal_details_provider.dart';
import 'package:kasax/kasax.dart';
import 'package:provider/provider.dart';
import 'package:flutter_icons/flutter_icons.dart';

import 'bottom_menu.dart';

/// metail details
/// used static route forward
class MetailsDetailV2 extends StatefulWidget {
  const MetailsDetailV2({Key? key}) : super(key: key);

  @override
  _MetailsDetailV2State createState() => _MetailsDetailV2State();
}

class _MetailsDetailV2State extends State<MetailsDetailV2> {
  var provider = MealDetailsProvider();

  @override
  Widget build(BuildContext context) {
    var args = ModalRoute.of(context)!.settings.arguments;
    if (args == null) {
      return Container(
        child: buildLoadingWidget(),
      );
    }

    return ChangeNotifierProvider(
      create: (BuildContext context) {
        return provider;
      },
      child: FutureBuilder(
        future: provider.featchMealDetail(args: args),
        builder:
            (BuildContext context, AsyncSnapshot<MealDetailData?> snapshot) {
          if (snapshot != null &&
              snapshot.connectionState == ConnectionState.done &&
              snapshot.hasData &&
              snapshot.data != null) {
            var data = snapshot.data!;
            if (data != null) {
              return Scaffold(
                body: ContentWidet(data!),
              );
            }
          }
          return Scaffold(
            body: Container(
              child: buildLoadingWidget(),
            ),
          );
        },
      ),
    );
  }
}

class ContentWidet extends StatefulWidget {
  MealDetailData data;

  ContentWidet(this.data, {Key? key}) : super(key: key);

  @override
  _ContentWidetState createState() => _ContentWidetState();
}

class _ContentWidetState extends State<ContentWidet> {
  ScrollController _scrollController = ScrollController();
  double opacity = 0;
  bool isShowTitle = false;

  @override
  void initState() {
    _scrollController.addListener(() {
      var val = _scrollController.position.pixels > 100.0 ? true : false;
      var tmp = _scrollController.position.pixels / 400.0;
      setState(() {
        isShowTitle = val;
        opacity = tmp < 0.8 ? tmp : 0.8;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        CustomScrollView(
          controller: _scrollController,
          slivers: [
            SliverToBoxAdapter(
              child: Column(
                children: [
                  AspectRatio(
                    aspectRatio: 1 / 1,
                    child: CachedNetworkImage(
                      fit: BoxFit.cover,
                      imageUrl: widget.data.cover_img!.big!,
                      placeholder: (
                        BuildContext context,
                        String url,
                      ) =>
                          Container(
                        color: Color(0xFFD6D6D6),
                        child: Center(
                          child: SizedBox(
                            width: 30,
                            height: 30,
                            child: CircularProgressIndicator(
                              color: Colors.blueGrey,
                            ),
                          ),
                        ),
                      ),
                    ),
                  ),
                  SizedBox(
                    height: 5,
                  ),
                  DescHeader(widget.data),
                  CookStepList(widget.data.cook_steps!)
                ],
              ),
            )
          ],
        ),
        Positioned(
          child: buildAppbar(),
          top: 0,
          left: 0,
          right: 0,
        ),
        Positioned(
          child: BottomMenu(widget.data),
          bottom: 0,
          left: 0,
          right: 0,
        ),
      ],
    );
  }

  buildAppbar() {
    return Container(
      color: Color.fromRGBO(255, 255, 255, opacity),
      padding: EdgeInsets.only(top: 23),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          // 返回按钮
          IconButton(
            onPressed: () {},
            icon: Icon(Icons.arrow_back_ios),
          ),
          isShowTitle
              ? Expanded(
                  child: Container(
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      CircleAvatar(
                        radius: 16,
                        backgroundImage:
                            NetworkImage(widget.data.author!.avatarUrl!),
                      ),
                      SizedBox(
                        width: 5,
                      ),
                      // 标题
                      Text(
                        widget.data.title!,
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                        style: TextStyle(
                      fontSize: 18,
                      fontWeight: FontWeight.w500,
                        ),
                      ),
                    ],
                  ),
                ))
              : Text(''),
          // 分享
          IconButton(
            onPressed: () {},
            icon: Icon(Icons.more_horiz),
          )
        ],
      ),
    );
  }
}

class DescHeader extends StatelessWidget {
  MealDetailData data;

  DescHeader(this.data, {Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    var secodaryIngredients = data.secondary_ingredient!
        .map((e) => "${e.title}: ${e.amount}")
        .toList();

    return Container(
      margin: EdgeInsets.only(top: 10, left: 16, right: 16, bottom: 10),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            "${data.title!} _ ${data.taste}",
            style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
          ),
          SizedBox(
            height: 10,
          ),
          Container(
            alignment: Alignment.bottomCenter,
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.end,
              children: [
                Expanded(
                    child: Row(
                  children: [
                    CircleAvatar(
                      radius: 30,
                      backgroundImage: NetworkImage(data.author!.avatarUrl!),
                    ),
                    SizedBox(
                      width: 10,
                    ),
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(data.author!.nickname!),
                        Text("${data.comment_amount}篇作品"),
                      ],
                    )
                  ],
                )),
                // buildMenuContainer()
                ActionChip(
                  label: Text(
                    "+ 关注",
                    style: TextStyle(color: Colors.white),
                  ),
                  onPressed: () {},
                  backgroundColor: Colors.red,
                ),
              ],
            ),
          ),
          SizedBox(
            height: 5,
          ),
          RichText(
            text: TextSpan(
                text: "烹饪方式:",
                style: TextStyle(color: Colors.black, fontSize: 16),
                children: [
                  TextSpan(
                    text: "${data.technology}",
                    style: TextStyle(color: Colors.grey, fontSize: 14),
                  )
                ]),
          ),
          RichText(
            text: TextSpan(
                text: "主料:",
                style: TextStyle(color: Colors.black, fontSize: 16),
                children: [
                  TextSpan(
                    text:
                        "${data.main_ingredient![0].title} ${data.main_ingredient![0].amount}",
                    style: TextStyle(color: Colors.grey, fontSize: 14),
                  )
                ]),
          ),
          // Text("辅料: $secodaryIngredients"),
          RichText(
            text: TextSpan(
                text: "辅料:",
                style: TextStyle(color: Colors.black, fontSize: 16),
                children: [
                  TextSpan(
                    text: "$secodaryIngredients",
                    style: TextStyle(color: Colors.grey, fontSize: 14),
                  )
                ]),
          ),
          RichText(
            text: TextSpan(
                text: "耗时:",
                style: TextStyle(color: Colors.black, fontSize: 16),
                children: [
                  TextSpan(
                    text: "${data.cooking_time}",
                    style: TextStyle(color: Colors.grey, fontSize: 14),
                  )
                ]),
          ),
          RichText(
            text: TextSpan(
                text: "关于:",
                style: TextStyle(color: Colors.black, fontSize: 16),
                children: [
                  TextSpan(
                    text: "${data.about_msj!.content!}",
                    style: TextStyle(color: Colors.grey, fontSize: 14),
                  )
                ]),
          ),
        ],
      ),
    );
  }

  Container buildMenuContainer() {
    return Container(
      padding: EdgeInsets.only(left: 16, right: 16, top: 5, bottom: 5),
      decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(17), color: Colors.red),
      child: RichText(
        textAlign: TextAlign.center,
        text: TextSpan(children: [
          TextSpan(text: "+", children: [TextSpan(text: " 关注")])
        ]),
      ),
    );
  }
}

class CookStepList extends StatelessWidget {
  List<CookStep> dataList;

  CookStepList(this.dataList, {Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ListView.builder(
      padding: EdgeInsets.zero,
      physics: NeverScrollableScrollPhysics(),
      shrinkWrap: true,
      itemBuilder: (context, index) {
        var cookStep = dataList![index];
        return Stack(
          children: [
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                AspectRatio(
                  aspectRatio: 1 / 1,
                  child: CachedNetworkImage(
                    fit: BoxFit.cover,
                    imageUrl: cookStep.pic_urls![0]!.big!,
                    placeholder: (
                      BuildContext context,
                      String url,
                    ) =>
                        Container(
                      color: Color(0xFFD6D6D6),
                      child: Center(
                        child: SizedBox(
                          width: 30,
                          height: 30,
                          child: CircularProgressIndicator(
                            color: Colors.blueGrey,
                          ),
                        ),
                      ),
                    ),
                  ),
                ),
                SizedBox(
                  height: 5,
                ),
                Text(
                  cookStep.content ?? "",
                  style:
                      TextStyle(fontSize: 16, letterSpacing: 1, wordSpacing: 3),
                ),
                Divider()
              ],
            ),
            Positioned(
              child: Stack(
                children: [
                  SizedBox(
                    width: 65,
                    height: 25,
                    child: Opacity(
                      opacity: 0.5,
                      child: Container(
                        decoration: BoxDecoration(
                            borderRadius: BorderRadius.only(
                              bottomRight: Radius.circular(16),
                              topRight: Radius.circular(16),
                            ),
                            color: Colors.white),
                      ),
                    ),
                  ),
                  Text(
                    cookStep.title ?? "",
                    style: TextStyle(
                        color: Colors.red,
                        fontWeight: FontWeight.bold,
                        fontSize: 16),
                  )
                ],
              ),
              top: 10,
            ),
          ],
        );
      },
      itemCount: dataList.length,
    );
  }
}
